package homeTask3;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class IntAsBytesSorter implements Sorter<byte[]> {

	class ByteComparator implements Comparator<byte[]>{

		@Override
		public int compare(byte[] o1, byte[] o2) {

			//find index of first not-zero digit in both numbers
			int i = 0;
			int j = 0;
			while(o1[i] - '0' == 0){
				if(i < o1.length - 1)
					i++;
				else{
					i = -1; 	//this number is 000...0
					break;
				}
			}
			
			while(o2[j] - '0' == 0){
				if(j < o2.length - 1)
					j++;
				else{
					j = -1;	//this number is 000...0
					if(i == -1)
						return 0;
					else
						return 1;
				}
			}
			
			if(i == -1 && j != -1)
				return -1;
			
			//compare it
			if(o1.length - i != o2.length - j)
				return (o1.length - i) - (o2.length - j);
			
			
			while(i < o1.length){
				if(o1[i] != o2[j]){
					return o1[i] - o2[j];
				}
				i++;
				j++;
			}
			return 0;
		}
	}
	

	@Override
	public List<byte[]> sort(List<byte[]> list) {
		Collections.sort(list, new ByteComparator());
		return list;
	}
}
